import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import router from 'umi/router';
import { fetchValidation } from '@/utils';
import {
    queryDetailInfo,
    saveCourier,
    updateCourier,
} from './service';

export type Effect = (
    action: AnyAction,
    effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
    namespace: string;
    state: {};
    effects: {
        fetch: Effect;
        saveOrUpdate: Effect;
    };
    reducers: {
        save: Reducer;
        clear: Reducer;
    };
}

const initData = {
    dataInfo: {},
};

const Model: ModelType = {
    namespace: 'courierCompanySaveAndEdit',

    state: initData,

    effects: {
        * fetch({ payload }, { call, put }) {
            const response = yield call(queryDetailInfo, payload);
            const data = fetchValidation(response);
            if (data) {
                yield put({
                    type: 'save',
                    payload: response.body,
                });
            }
        },

        * saveOrUpdate({ payload }, { call, put }) {
            const formData = new FormData();
            Object.entries(payload).map((item: any) => (
                formData.append(item[0], item[1])
            ));
            const response = yield call((payload.id ? updateCourier : saveCourier), { body: formData });
            const data = fetchValidation(response);
            if (data) {
                message.success(payload.id ? '修改成功' : '新增成功');
                yield put({
                    type: 'global/setPath',
                });
                router.goBack();
            }
        },
    },

    reducers: {
        save(state, action) {
            return {
                ...state,
                dataInfo: action.payload,
            };
        },

        clear() {
            return ({
                initData: {
                    dataInfo: {},
                },
            });
        },
    },
};

export default Model;
